<template>
  <div class="app-main-container">
    <QueryForm v-model="filters" :query-form-config="queryFormConfig" @handleQuery="getList(1)" @clear="clearFilters" />
    <div v-if="meta.indexOf('AccountAdd') > -1" class="doumee-table-buttons">
      <el-button v-preventReClick type="primary" @click="toAccountAdd(0)">{{
        $t("message.add")
      }}</el-button>
    </div>
    <el-table ref="table" v-loading="listLoading" :data="list" border fit :header-row-class-name="'table-header'" class="doumee-element-table">
      <el-table-column align="center" :label="$t('message.userface')" width="120" show-overflow-tooltip prop="faceImg2">
        <template v-if="scope.row.faceImg2" slot-scope="scope">
          <el-image fit="contain" :src="scope.row.faceImg2" :preview-src-list="[scope.row.faceImg2]" />
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.loginUser')" prop="userName" min-width="120" show-overflow-tooltip fixed="left" />
      <el-table-column align="center" :label="$t('message.userName')" prop="nickName" min-width="120" show-overflow-tooltip fixed="left" />
      <el-table-column align="center" :label="$t('message.realname')" prop="realName" min-width="120" show-overflow-tooltip fixed="left" />
      <el-table-column align="center" :label="$t('message.phone')" prop="phone" show-overflow-tooltip min-width="140" />
      <el-table-column align="center" :label="$t('message.relerole')" prop="roleList_" show-overflow-tooltip min-width="200" />
      <el-table-column align="center" :label="$t('message.releVenue')" prop="stadiumList_" show-overflow-tooltip min-width="200" />
      <el-table-column align="center" :label="$t('message.relexpz')" prop="printerName" show-overflow-tooltip min-width="200" />
      <el-table-column align="center" :label="$t('message.status')" min-width="120">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="'1'" :inactive-value="'0'" :disabled="meta.indexOf('AccountOnOff') == -1" @change="toAccountStatus($event, scope.row.id)" />
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('message.userExplain')" prop="info" min-width="300" show-overflow-tooltip />
      <el-table-column :label="$t('message.handle')" :width="$i18n.locale === 'ZH'? 350 : 540" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button v-if="meta.indexOf('AccountEdit') > -1" v-preventReClick type="text" @click="toAccountAdd(1, scope.row)">{{ $t("message.edit") }}</el-button>
            <el-button v-if="meta.indexOf('AccountEditRPwd') > -1" v-preventReClick type="text" @click="toAccountRepassword(scope.row)">{{ $t("message.resetPsd") }}</el-button>
            <el-button v-if="meta.indexOf('AccountDel') > -1" v-preventReClick type="text" style="color: red" @click="toAccountDelete(scope.row.id)">{{ $t("message.del") }}</el-button>
            <el-button v-if="meta.indexOf('AccoundInOutRecord') > -1" v-preventReClick type="text" @click="jccBtn(scope.row.id)"> {{ $t("message.jccjl") }}</el-button>
            <el-button v-preventReClick type="text" @click="tbry(scope.row.id)">{{ $t("message.issueDevice") }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <Pagination :total="total" :page="pagination.page" @current-change="getList" @SizeChange="handleSizeChange" />
    <!-- 进出场记录 -->
    <el-dialog :close-on-click-modal="modalDialog" :lose-on-press-escape="modalDialog" :title=" $t('message.jccjl') " :visible.sync="showAddAccounts" width="850px" @closed="cancelAddAccount">
      <el-table ref="table" v-loading="listLoading" :data="approachList" border fit :header-row-class-name="'table-header'" class="doumee-element-table">
        <!-- <el-table-column align="center" :label="$t('message.loginUser')" prop="userName" min-width="120" show-overflow-tooltip /> -->
        <!-- <el-table-column align="center" :label="$t('message.userName')" prop="nickName" min-width="120" show-overflow-tooltip /> -->
        <el-table-column align="center" :label="$t('message.yhxx')" prop="member" min-width="120" show-overflow-tooltip />
        <!-- <el-table-column align="center" :label="$t('message.realname')" prop="realName" min-width="120" show-overflow-tooltip /> -->
        <!-- <el-table-column align="center" :label="$t('message.phone')" prop="phone" show-overflow-tooltip min-width="140" /> -->
        <!-- <el-table-column align="center" :label="$t('message.relerole')" prop="roleList_" show-overflow-tooltip min-width="200" /> -->
        <el-table-column align="center" :label="$t('message.venue')" prop="venueName" show-overflow-tooltip min-width="200" />
        <el-table-column align="center" label="进场时间" prop="inTime" show-overflow-tooltip min-width="200" />
        <el-table-column align="center" label="出场时间" prop="outTime" show-overflow-tooltip min-width="200" />
        <!-- <el-table-column align="center" :label="$t('message.relexpz')" prop="printerName" show-overflow-tooltip min-width="200" />
        <el-table-column align="center" :label="$t('message.userExplain')" prop="info" min-width="300" show-overflow-tooltip /> -->
      </el-table>
      <Pagination :total="totals" :page="paginations.page" @current-change="getApproachList" @SizeChange="handleSizeChanges" />
    </el-dialog>
    <!-- 进出场记录 -->
    <!-- 新增 编辑 用户 -->
    <el-dialog :close-on-click-modal="modalDialog" :lose-on-press-escape="modalDialog" :title="addEditType ? $t('message.editUser') : $t('message.addUser')" :visible.sync="showAddAccount" width="850px" @closed="cancelAddAccount">
      <el-form ref="ruleForm" :model="formAddAccount" :rules="rules" label-width="auto">
        <el-form-item :label="$t('message.userface')" prop="faceImg2">
          <transition name="fade">
            <Cropper v-if="dialogCropperVisible" :option-img="optionImg" :fileinfo="fileinfo" use-type="USER_IMG" :fixed-number="[32, 32]" @formSubmit="cropperSubmit" @formClose="cropperClose" />
          </transition>
          <div class="df_ac">
            <el-upload class="device-uploader" :action="uploadFileUrl" :data="uploadParam" :auto-upload="false" :show-file-list="false" accept=".jpg,.png" :on-change="addFileChange">
              <i class="el-icon-plus uploader-icon" />
              <div v-show="formAddAccount.faceImg2" class="file" :style="
                  'background-image: url(' + formAddAccount.faceImg2 + ')'
                ">
                <div class="delete">
                  <i class="el-icon-delete icon" @click.stop="deleteDeviceConfigAddImage" />
                </div>
              </div>
            </el-upload>
            <div class="placeholder9">
              <div>{{ $t("message.placeSize") }}</div>
              <div>{{ $t("message.placeFormat") }}</div>
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.loginUser')" prop="userName">
          <el-input v-model="formAddAccount.userName" maxlength="50" />
          <div>
            <div v-if="
                addEditType &&
                  formAddAccount.userNameTemp != formAddAccount.userName
              " class="red fs_12">
              {{ $t("message.placeDefPsd") }}
            </div>
            <div v-else class="placeholder9">
              {{ $t("message.placePsdCon") }}
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.userName')" prop="nickName">
          <el-input v-model="formAddAccount.nickName" maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('message.realname')">
          <el-input v-model="formAddAccount.realName" maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('message.identityCard')">
          <el-input v-model="formAddAccount.identityNumber" maxlength="50" />
        </el-form-item>

        <el-form-item :label="$t('message.icNumber')">
          <el-input v-model="formAddAccount.icNumber" maxlength="50" />
        </el-form-item>
        <el-form-item label="是否限制进出场" prop="inLimitFlag">
          <el-radio v-model="formAddAccount.inLimitFlag" label="0" @change="handleLimitChange">不限制</el-radio>
          <el-radio v-model="formAddAccount.inLimitFlag" label="1" @change="handleLimitChange">限制</el-radio>
        </el-form-item>
        <el-form-item v-if="formAddAccount.inLimitFlag=='1'" label="关联闸机" prop="inLimitEntryCodes">
          <el-select v-model="formAddAccount.inLimitEntryCodes" value-key="code" :placeholder="$t('message.xzcj')" multiple style="width: 100%" clearable>
            <el-option v-for="item in gateListData" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.phone')" prop="phone">
          <el-input v-model="formAddAccount.phone" type="phone" maxlength="11" />
        </el-form-item>
        <el-form-item :label="$t('message.relerole')" prop="roleIds">
          <el-select v-model="formAddAccount.roleIds" value-key="id" :placeholder="$t('message.chooseRole')" multiple style="width: 100%" clearable>
            <el-option v-for="item in roleListData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.releVenue')" prop="list">
          <el-checkbox-group v-model="formAddAccount.list">
            <el-checkbox v-for="item in venueListData" :key="item.id" :label="item.id" :name="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('message.relexpz')">
          <el-select v-model="formAddAccount.printerId" :placeholder="$t('message.chooseReceipt')" clearable style="width: 100%">
            <el-option v-for="item in printerListb" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.userStatus')">
          <el-switch v-model="formAddAccount.status" :active-value="'1'" :inactive-value="'0'" />
        </el-form-item>
        <el-form-item :label="$t('message.userExplain')">
          <el-input v-model="formAddAccount.info" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="cancelAddAccount">{{ $t("message.qx") }}</el-button>
        <el-button :loading="subLoading" type="primary" @click="confirmAddAccount">{{ $t("message.qd") }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  uploadFile,
  venueList,
  roleList,
  gateData,
  gateApproach,
  printerList,
  accountList,
  syncUserToDev,
  accountAdd,
  accountRepassword,
  accountStatus,
  accountEdit,
  accountDelete,
  accountRoleDelete
} from '@/api'
import Cropper from '@/components/cropper'
import { parseTime } from '@/utils'
import Pagination from '@/components/paginations'
import { queryFormConfig } from './config'
export default {
  name: 'AccountList',
  components: {
    Cropper,
    Pagination
  },
  data () {
    return {
      queryFormConfig,
      modalDialog: this.$store.state.app.dialog,
      subLoading: false,
      dialogCropperVisible: false,
      param: {},
      meta: [],
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'USER_IMG'
      },
      cur_page: 1,
      venueListData: [],
      roleListData: [],
      gateListData: [],
      list: [],
      filters: {
        userName: ''
      },
      pagination: {
        firstQueryTime: new Date(),
        page: 1,
        rows: 10
      },
      paginations: {
        firstQueryTime: new Date(),
        page: 1,
        rows: 10
      },
      total: 0,
      totals: 0,
      addEditType: 0,
      showAddAccount: false,
      showAddAccounts: false,
      imageList: [],
      JcUserId: '',
      approachList: [],
      formAddAccount: {
        userName: '',
        realName: '',
        phone: '',
        roleIds: [],
        venueIds: [],
        list: [],
        status: '1',
        info: '',
        inLimitFlag: '0',
      },
      printerListb: [],
      rules: {
        userName: [
          // { required: true, message: '请输入登陆账号', trigger: 'blur' }
          { required: true, message: this.translate('placeLoginUser'), trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        nickName: [
          // { required: true, message: '请输入用户昵称', trigger: 'blur' }
          { required: true, message: this.translate('placeUsername'), trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        realName: [
          // { required: true, message: this.translate('qsr'), trigger: 'blur' }
          { required: true, message: this.translate('placeRealname'), trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        identityNumber: [
          // { required: true, message: this.translate('placeIdCard'), trigger: 'blur' },
          { required: true, message: this.translate('placeIdCard'), trigger: 'blur' },
          {
            required: true,
            pattern:
              /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
            message: this.translate('placeIdCardPs'),
            trigger: 'blur'
          }
        ],
        phone: [
          // { required: true, message: this.translate('placePhone'), trigger: 'blur' }
          { required: true, message: this.translate('placePhone'), trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleIds: [
          {
            type: 'array',
            required: true,
            message: this.translate('placeReleRole'),
            trigger: 'change'
          }
        ],
        list: [
          {
            type: 'array',
            required: true,
            message: this.translate('placeVenue'),
            trigger: 'change'
          }
        ]
      },
      venueIdsAll: [],
    }
  },
  created () {
    this.meta = this.$route.meta.buttons || []
    this.getPrinterList()
    this.getList(1)
    this.getRoleList()

    this.getVenueList()
  },
  mounted () {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated () {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    handleLimitChange (value) {
      if (value === '0') {
        this.formAddAccount.inLimitEntryCodes = [];
      }
    },
    getPrinterList () {
      printerList({}).then((res) => {
        if (res.errorCode !== '000000') return
        this.printerListb = res.recordList
      })
    },
    tbry (userId) {
      syncUserToDev({
        param: {
          type: '0',
          userType: '0',
          userId
        }
      }, sessionStorage.getItem('venueId')).then(res => {
        if (res.errorCode === '000000') {
          // this.$message.success('同步成功')
          this.$message.success(this.translate('syncSuccess'))
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 上传成功
    uploadSuccess (response, file, fileList) {
      if (response.success) {
        this.$set(this.formAddAccount, 'faceImg2', response.showUrl)
        this.$set(this.formAddAccount, 'faceImg', response.insertUrl)
        this.$refs.ruleForm.clearValidate()
      } else {
        // this.$message.error(response.msg || this.translate('scsb'))
        this.$message.error(response.msg || this.translate('scsb'))
      }
    },
    // 裁剪确定按钮
    cropperSubmit (config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.formAddAccount, 'faceImg2', config.showUrl)
        this.$set(this.formAddAccount, 'faceImg', config.insertUrl)
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      } else {
        // this.$message.error(config.msg || this.translate('scsb'))
        this.$message.error(config.msg || this.translate('scsb'))
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose () {
      this.dialogCropperVisible = false
    },
    async addFileChange (file, fileList) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 删除场馆设施已上传图片
    deleteDeviceConfigAddImage () {
      this.$set(this.formAddAccount, 'faceImg2', '')
      this.$set(this.formAddAccount, 'faceImg', '')
    },
    // 获取场馆列表
    getVenueList () {
      venueList({ param: {} }).then((res) => {
        if (res.errorCode !== '000000') return
        this.venueListData = res.recordList
        // 获取场馆所以id
        const newIdArray = this.venueListData.map(item => item.id);
        this.venueIdsAll = newIdArray
        this.getGateList()
      })
    },
    // 获取角色列表
    getRoleList () {
      roleList({}).then((res) => {
        if (res.errorCode !== '000000') return
        this.roleListData = res.recordList
      })
    },

    // 获取闸机列表
    getGateList () {
      gateData({ param: { venueIds: this.venueIdsAll } }).then((res) => {
        if (res.errorCode !== '000000') return
        this.gateListData = res.recordList
      })
    },
    // 获取员工进出场记录
    getApproachList (page) {
      const { paginations } = this
      if (page) {
        paginations.page = page
        this.paginations.page = page
      }
      gateApproach({ pagination: paginations, param: { user: this.JcUserId } }).then((res) => {
        if (res.errorCode !== '000000') return
        this.approachList = res.recordList
        this.totals = res.totalCount
      })
    },
    // 清空筛选项
    clearFilters () {
      this.filters = {}
      this.getList(1)
    },
    handleSizeChange (value) {
      this.pagination.rows = value
      this.getList(1)
    },
    handleSizeChanges (value) {
      this.paginations.rows = value
      this.getApproachList(1)
    },
    // 获取账号列表
    getList (page) {
      const { pagination, filters: param } = this
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      if (pagination.page === 1) {
        pagination.firstQueryTime = parseTime(new Date())
      }
      this.listLoading = true
      accountList({ pagination, param }).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          for (const i in res.recordList) {
            const { stadiumList } = res.recordList[i]
            const { roleList } = res.recordList[i]
            res.recordList[i].stadiumList_ = []
            for (const j in stadiumList) {
              res.recordList[i].stadiumList_.push(stadiumList[j].name)
            }
            res.recordList[i].stadiumList_ =
              res.recordList[i].stadiumList_.join('/')

            res.recordList[i].roleList_ = []
            for (const j in roleList) {
              res.recordList[i].roleList_.push(roleList[j].name)
            }
            res.recordList[i].roleList_ = res.recordList[i].roleList_.join('/')
          }
          this.list = res.recordList
          this.total = res.totalCount
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    change () {
      const { venueListData } = this
      const param = { ...this.formAddAccount }
      param.list = []
      for (const i in venueListData) {
        if (venueListData[i].checked) {
          param.list.push(venueListData[i].id)
        }
      }
      this.$set(this.formAddAccount, 'list', param.list)
    },
    // 重置密码
    toAccountRepassword (row) {
      this.$confirm(`${this.translate('startReset')}${row.userName}${this.translate('psdResetPlace')}`, this.translate('ts'), {
        confirmButtonText: this.translate('qd'),
        cancelButtonText: this.translate('qx'),
        type: 'warning'
      }).then(() => {
        accountRepassword({ param: { userId: row.id } }).then((res) => {
          if (res.errorCode !== '000000') return
          this.$message.success(this.translate('resetPsdSuccess'))
        })
      })
    },
    // 启用禁用
    toAccountStatus (status, userId) {
      accountStatus({ param: { status, userId } })
    },
    jccBtn (e) {
      this.JcUserId = e
      this.getApproachList(1)
      this.showAddAccounts = true


    },
    // 新增 编辑 用户
    toAccountAdd (type, row) {
      this.addEditType = type
      this.showAddAccount = true
      // 编辑 数据回显
      if (row) {
        const { roleList, stadiumList } = row
        let code = []
        if (Array.isArray(row.inLimitEntrys) && row.inLimitEntrys.length > 0) {
          code = row.inLimitEntrys.map(item => item.code);
        }
        row.roleIds = []
        row.list = []
        for (const item of roleList) {
          row.roleIds.push(String(item.roleId))
        }
        for (const item of stadiumList) {
          row.list.push(item.stadiumId)
        }
        // for (const i in this.venueListData) {
        //   if (stadiumList_.includes(this.venueListData[i].id)) {
        //     this.$set(this.venueListData[i], 'checked', true)
        //   }
        // }
        // this.change()
        this.formAddAccount = { ...row, userNameTemp: row.userName, inLimitEntryCodes: code }
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate()
        })
      }
    },

    // 取消 新增 编辑 用户
    cancelAddAccount () {
      for (const item of this.venueListData) {
        item.checked = false
      }
      this.formAddAccount = {
        userName: '',
        realName: '',
        phone: '',
        roleIds: [],
        list: [],
        inLimitEntryCodes: [],
        status: '1',
        inLimitFlag: '0',
        info: ''
      }
      this.showAddAccount = false
    },
    // 确认新增 编辑 用户
    confirmAddAccount () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const { addEditType } = this
          const param = { ...this.formAddAccount }
          this.subLoading = true
          if (addEditType) {
            accountEdit({ param }).then((res) => {
              this.subLoading = false
              if (res.errorCode !== '000000') return
              this.showAddAccount = false
              this.getList(1)
            }, () => {
              this.subLoading = false
            })
          } else {
            accountAdd({ param }).then((res) => {
              this.subLoading = false
              if (res.errorCode !== '000000') return
              this.showAddAccount = false
              this.getList(1)
            }, () => {
              this.subLoading = false
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除用户
    toAccountDelete (userId) {
      this.$confirm(this.translate('userdelPlace'), this.translate('ts'), {
        confirmButtonText: this.translate('qd'),
        cancelButtonText: this.translate('qx'),
        type: 'warning'
      })
        .then(() => {
          // 删除绑定角色
          accountRoleDelete({ param: { userId } }).then((ress) => {
            if (ress.errorCode !== '000000') return
            // 删除账号
            accountDelete({ param: { id: userId } }).then((resss) => {
              if (resss.errorCode !== '000000') return
              this.$message.success(this.translate('delScs'))
              this.getList(1)
            })
          })
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: this.translate('canceledDel')
          // })
        })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
::v-deep.el-radio__original {
  display: none !important;
}

::v-deep.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>

